<?php
namespace app\controllers;

use app\models\NewsRecorder;

class NewsController extends BaseController{
    public function actionAdd(){
        $post = \Yii::$app->request->post();
        $id = intval($post['NewsRecorder']['id']);
        if($id){
            $model = NewsRecorder::find()->where('id=:id',[':id' => $id])->one();
            if(!$model){
                $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
                return json_encode($result);
            }
        }else{
            $model = new NewsRecorder();
            $model->addtime = time();
        }
        $result = $model->add($post);
        return json_encode($result);
    }

    public function actionList(){
        $post = \Yii::$app->request->post('page');
        $page = intval($post['page'])-1;
        $pagesize = intval($post['pagesize']);
        $offset = $page*$pagesize;
        $list = NewsRecorder::find();
        $count = $list->count();
        $list = $list->limit($pagesize)->offset($offset)->orderBy('addtime DESC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $v['news_type'] = json_decode($v['news_type'],true);
            $list[$k]['thumb_pic'] = empty($v['thumb_pic'])?"":str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
            $arr = [];
            foreach($v['news_type'] as $t){
                switch ($t){
                    case 1:
                        $arr[]="推荐";
                        break;
                    case 2:
                        $arr[] = "热门";
                        break;
                }
            }
            $list[$k]['news_type'] = implode(",",$arr);
        }
        $result = ['result'=>1,'data'=>$list,'count'=>$count];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }

    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $model = NewsRecorder::find()->where('id=:id',[':id' => $id])->asArray()->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model['news_type'] = json_decode($model['news_type'],true);
        $model['thumb_pic'] = empty($model['thumb_pic'])?"":str_replace("../",\Yii::$app->params['pic_url'],$model['thumb_pic']);
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }

    public function actionDel(){
        $id = \Yii::$app->request->post('id');
        $model = NewsRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>-0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model->delete();
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }




}